/**
 * 获取日志
 * 
 * /admin/getLog
 * 
 */

const Log = require('../../../models/log')
const utils = require('../../../utils/index')
const $ = require('../../../utils/common')
const Sequelize = require('sequelize')
const Op = Sequelize.Op

const get_log = function(req,res) {
    try{
        var query = {}
        if (req.query.user_name) { 
            query['user_name'] = req.query.user_name
        }
        const start_time = Date.parse(new Date(req.query.start_time)) || Date.parse(new Date('2020-01-05 13:10:43'))
        const end_time = Date.parse(new Date(req.query.end_time)) || Date.parse(new Date())
        // req.query.page
        var offset = 1
        var limit = parseInt(req.query.size)
        if (req.query.page > 1) {
            offset = parseInt(req.query.size) * (parseInt(req.query.page) - 1)
        } else if (req.query.page == 1) {
            offset = 0
        }
        if (req.query.size && req.query.page) {
            Log.findAndCountAll({
                offset: offset,
                limit: limit,
                order: [
                    ['createdAt', 'DESC'],
                ],
                where: {
                    createdAt: {
                        [Op.lt]: new Date(end_time),
                        [Op.gte]:new Date(start_time)
                    },
                    user_name: {
                        [Op.like]: '%' + (query.user_name == undefined ? '' : query.user_name) + '%'
                    },
                },
                attributes: ['user_name', 'user_ip', 'request_module', 'request_behavior', 'request_status', 'createdAt'],
            }).then(result => {
                res.json({
                    code: 200,
                    message: 'success',
                    data: result.rows,
                    total: result.count
                })
                // 生成一条操作日志
                // 翻页不生产日志
                if (req.query.page == '1') {
                    utils.create_a_log(req, '日志', '浏览')
                }
            })
            return
        } else {
            res.json({
                message: '参数错误'
            })
            return
        }
    }
    catch(error) {
        $.sendMessage(res, 1015, 'error' + error)
        return
    }
}

module.exports = get_log